package cn.com.dealme.domain.repository.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.zzm.util.PageHelper;

import cn.com.dealme.domain.model.User;
import cn.com.dealme.domain.persistence.CommodityPersistenceProxy;
import cn.com.dealme.domain.persistence.UserPersistenceProxy;
import cn.com.dealme.domain.repository.IUserRepository;

public class UserRepositoryImpl implements IUserRepository {
	
	private static final int pageSize = 20;
	
	private Session session;

	public void delete(Long id) {
		session.delete(session.get(UserPersistenceProxy.class, id));
	}

	public void delete(Long[] ids) {
		for (Long id : ids) {
			session.delete(session.get(CommodityPersistenceProxy.class, id));
		}
	}

	public User find(Long id) {
		return (User) session.get(UserPersistenceProxy.class, id);
	}

	@SuppressWarnings("unchecked")
	public User findByAccount(String account) {
		Criteria dc = session.createCriteria(UserPersistenceProxy.class);
		dc.add(Restrictions.eq("accountInfo.account", account));
		List<User> users = dc.list();
		if(null == users || 0 == users.size()) {
			return null;
		}
		return users.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<User> queryByPage(int page, int size) {
		String entityName = session.getSessionFactory().getClassMetadata(
				UserPersistenceProxy.class).getEntityName();
		
		return session.createQuery("from " + entityName).setFirstResult(
				PageHelper.getFirstResult(page, pageSize)).setMaxResults(
						pageSize).list();
	}

	@SuppressWarnings("unchecked")
	public List<User> queryLike(String account, int page, int size) {
		Criteria dc = session.createCriteria(UserPersistenceProxy.class);
		dc.setFirstResult(PageHelper.getFirstResult(page, pageSize));
		dc.setMaxResults(pageSize);
		dc.add(Restrictions.like("account", account));
		return dc.list();
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}
}
